package com.max.xihu;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @Author: Max
 * @Date: 2020-03-12 21:18
 * @Description:
 */
@RestController
public class RedisController {

    @Resource
    Redisson redisson;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping("/deduct")
    public String deductStock(){
        String stockKey = "stockKey";
        RLock lock = redisson.getLock(stockKey);
        lock.lock();
        try {
            int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock"));
            if(stock > 0){
                int realStock = stock - 1;
                stringRedisTemplate.opsForValue().set("stock",String.valueOf(realStock));
                System.out.println("扣减库存成功，剩余库存:"+realStock);
            }else{
                System.out.println("扣减失败，库存不足");
            }
        }finally {
            lock.unlock();
        }
        return "success:" + System.currentTimeMillis();
    }


}
